#include <iostream>
#include <string>
#include <ctime>
#include <unistd.h>

#include "Socket.hpp"
#include "Protocol.hpp"
#include "Log.hpp"
#include "InetAddr.hpp"

using namespace Space_Protocol;
using namespace Space_Socket;

void Usage(const std::string &tip)
{
    std::cout << "Please Use\n\t" << tip << " serverip serverport\n"
              << std::endl;
}

int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage(argv[0]);
        exit(USAGE_ERROR);
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);

    // 创建套接字

    InetAddr server(serverip, serverport);
    std::unique_ptr<Socket> tcli = std::make_unique<TcpSocket>();
    bool ret = tcli->BuildTcpClientSocket(server);

    Factory factory;
    //
    std::string inbuffer; // 接收缓冲区
    while (ret)
    {

        std::string str;
        for (int i = 0; i < 5; ++i)
        {
            sleep(1);
            std::string send_str;

            // 1.构建一个请求
            auto req = factory.BuildRequest();

            // 2.序列化

            req->Serialize(&send_str);
            std::cout << "Serialize:\n"
                      << send_str;

            // 3.加报头
            send_str = Encode(send_str);
            std::cout << "Encode:\n"
                      << send_str;

            str += send_str;
            std::cout << "=====================================" << std::endl;
        }
        
        tcli->Send(str);

        for (int i = 0; i < 5; ++i)
        {
            // 5.接收
            int n = tcli->Recv(&inbuffer);
            if (n <= 0)
                break;

            // 6.去报头
            std::string package = Decode(inbuffer);
            if (package.empty())
                continue;

            // 7.反序列化
            auto resp = factory.BuildResponse();
            resp->Re_Serialize(package);

            //
            std::cout << resp->_result << "[" << resp->_code << "]" << std::endl;
        }
    }

    return 0;
}